package com.editso.haier.service;


import com.editso.haier.result.Result;
import com.editso.haier.storage.Storage;
import com.editso.haier.storage.UpFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 文件相关服务
 */
@Service
public class FileService {
    private Storage storage;

    @Autowired
    public void setStorage(Storage storage) {
        this.storage = storage;
    }

    public String save(String savePath, UpFileItem file, boolean require)
            throws IOException, NullPointerException {
        if (file == null || file.getName() == null || storage == null) throw new NullPointerException();
        String fileName = file.geHexFileName();
        return storage.exists(savePath,fileName)
                ? fileName
                : storage.save(savePath, fileName, file.stream(), file.getContentType());
    }

    public ResponseEntity<Object> download(String accessPath, String fileName, String contentType){
        try {
            if (!(storage == null || !storage.exists(accessPath, fileName))){
                Storage.FileItem item = storage.get(accessPath, fileName);
                InputStreamSource streamSource = new InputStreamResource(item.stream());
                MediaType type = null;
                try {
                    type = MediaType.valueOf(contentType);
                }catch (Exception e){
                    try {
                        type = MediaType.valueOf(item.getContentType());
                    }catch (Exception err){
                        type = MediaType.valueOf("application/octet-stream");
                    }
                }
                return ResponseEntity.ok() .contentLength(item.getLength())
                        .contentType(type)
                        .body(streamSource);
            }
        } catch (IOException ignore) {

        }
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(Result.failure("资源不存在!"));
    }
}
